/**
 * 
 */
package com.eis.admin.mvc.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.eis.admin.mvc.bean.UserBean;
import com.eis.admin.mvc.common.utils.MVCConstants;
import com.eis.admin.mvc.controller.base.MVCBaseController;
import com.eis.persist.dao.UserDAO;
import com.eis.persist.dao.impl.UserDAOImpl;
import com.eis.persist.model.user.PersistBizGroup;
import com.eis.persist.model.user.PersistSysGroup;
import com.eis.persist.model.user.PersistUser;
import com.eis.util.EncryptUtil;

/**
 * @author sh-panwei01
 *
 */
@Controller
public class UserAdminController extends MVCBaseController {
	private static final Logger logger = LoggerFactory
			.getLogger(UserAdminController.class);
	private UserDAO userDAO;

	@Override
	public void setFunctionDataSource(JdbcTemplate functionDataSource) {
		this.functionDataSource = functionDataSource;
		userDAO = new UserDAOImpl(this.functionDataSource);
	}
	
	
	@RequestMapping(value = "/userAdminIntroduction")
	public ModelAndView userAdminIntroduction(Model model, HttpServletRequest request) {
		return new ModelAndView("/user/userAdminIntroduction");
	}
	
	@RequestMapping(value = "/userHome")
	public ModelAndView userHome(@ModelAttribute("searchUser") UserBean userBean, Model model, HttpServletRequest request) {
		UserBean filter = null;
		if (userBean != null
				&& ((userBean.getUserName() != null && userBean.getUserName()
						.length() > 0) || userBean.getSysGroup() != 0 || userBean
						.getBizGroup() != 0)) {
			filter = userBean;
		} else {
			filter = new UserBean(null, 0, 0);
		}
		PersistUser dbFilter = new PersistUser(filter);
		List<PersistUser> persistUsers = userDAO.getUserForList(dbFilter, 1, 100);

		model.addAttribute("userList", persistUsers);

		List<PersistSysGroup> persistSysGroups = userDAO.getSysGroups();

		List<PersistBizGroup> persistBizGroups = userDAO.getBizGroups();
		PersistBizGroup noBizGroup = new PersistBizGroup();
		noBizGroup.setId(-1);
		noBizGroup.setName("No Bussiness Group");
		persistBizGroups.add(0, noBizGroup);

		model.addAttribute("sysGroups", persistSysGroups);
		model.addAttribute("bizGroups", persistBizGroups);
		return new ModelAndView("/user/userHome", "command", filter);
	}
	
	
	@RequestMapping(value = "/createUser", method = RequestMethod.GET)
	public ModelAndView createUser(Model model, HttpSession session) {

		List<PersistSysGroup> persistSysGroups = userDAO.getSysGroups();

		List<PersistBizGroup> persistBizGroups = userDAO.getBizGroups();
		PersistBizGroup noBizGroup = new PersistBizGroup();
		noBizGroup.setId(0);
		noBizGroup
				.setName("--not selected, if this user don't need access any function--");
		persistBizGroups.add(0, noBizGroup);
		model.addAttribute("sysGroups", persistSysGroups);
		model.addAttribute("bizGroups", persistBizGroups);
		return new ModelAndView("/user/createUser", "command", new UserBean());
	}
	
	@RequestMapping(value = "/editUser", method = RequestMethod.GET)
	public ModelAndView editUser(Model model, HttpSession session, HttpServletRequest request) {
		String userId = request.getParameter("id");
		
		boolean userIdCorrect = true;
		int userIntId = 0;
		try {
			userIntId = Integer.parseInt(userId);
			userIdCorrect = userIntId > 0;
		} catch (NumberFormatException ne) {
			userIdCorrect = false;
		}
		
		if (userIdCorrect) {
			try {
				PersistUser persistUser = userDAO.getUserForEdit(userIntId);
				if (persistUser != null) {
					List<PersistSysGroup> persistSysGroups = userDAO.getSysGroups();

					List<PersistBizGroup> persistBizGroups = userDAO.getBizGroups();
					PersistBizGroup noBizGroup = new PersistBizGroup();
					noBizGroup.setId(0);
					noBizGroup
							.setName("--not selected, if this user don't need access any function--");
					persistBizGroups.add(0, noBizGroup);
					model.addAttribute("sysGroups", persistSysGroups);
					model.addAttribute("bizGroups", persistBizGroups);
					model.addAttribute("userName", persistUser.getName());
					
					UserBean userBean = new UserBean(persistUser);
					return new ModelAndView("/user/editUser", "command", userBean);
				}
			} catch (Throwable t) {
				logger.error("Error when edit user, id: " + userId, t);
				return new ModelAndView(
						"redirect:" + appPrefix + "/userHome",
						prepareRedirectErrorMessage("Error occured when forward to edit user, please try latter!"));
			}
			
		} 
		
		return new ModelAndView(
					"redirect:" + appPrefix + "/userHome",
					prepareRedirectErrorMessage("Please select a user first!"));
	}
	
	@RequestMapping(value = "/submitCreateUser")
	public ModelAndView submitCreateUser(Model model,
			@ModelAttribute("createUser") UserBean userBean,
			HttpServletRequest request) {
		PersistUser persistUser = new PersistUser();
		UserDAO userDAO = new UserDAOImpl(this.functionDataSource,
				((PersistUser) request.getSession().getAttribute(
						MVCConstants.USER_SESSION_KEY)).getName());

		// TODO: validate
		persistUser.setName(userBean.getUserName());
		persistUser.setPassword(EncryptUtil.encryptPassword(userBean.getPassword()));
		persistUser.setEmail(userBean.getEmail());
		if (userBean.getSysGroup() > 0) {
			PersistSysGroup persistSysGroup = new PersistSysGroup();
			persistSysGroup.setId(userBean.getSysGroup());
			persistUser.setSysGroup(persistSysGroup);
		}

		if (userBean.getBizGroup() > 0) {
			PersistBizGroup persistBizGroup = new PersistBizGroup();
			persistBizGroup.setId(userBean.getBizGroup());
			persistUser.setBizGroup(persistBizGroup);
		}

		userDAO.createUser(persistUser);
		return new ModelAndView("redirect:" + appPrefix + "/userHome", prepareRedirectWarnMessage("User '" + persistUser.getName()
				+ "' have been created successfully!"));
	}
	
	@RequestMapping(value = "/deleteUser")
	public ModelAndView deleteUser(Model model, HttpServletRequest request) {
		PersistUser currentUser = (PersistUser) request.getSession().getAttribute(
				MVCConstants.USER_SESSION_KEY);
		UserDAO userDAO = new UserDAOImpl(this.functionDataSource, currentUser.getName());
		String userId = request.getParameter("id");
		if (String.valueOf(currentUser.getId()).equals(userId)) {
			return new ModelAndView(
					"redirect:" + appPrefix + "/userHome",
					prepareRedirectErrorMessage("You cannot delete yourself!"));
		}
		
		try {
			if (userDAO.deleteUserById(Integer.parseInt(userId))) {
				return new ModelAndView(
						"redirect:" + appPrefix + "/userHome",
						prepareRedirectWarnMessage("User have been deleted successfully!"));
			} else {
				logger.info("No user found when delete user, id: " + userId);
				return new ModelAndView(
						"redirect:" + appPrefix + "/userHome",
						prepareRedirectWarnMessage("No user found for delete!"));
			}
		} catch (Throwable t) {
			logger.error("Error when delete user, id: " + userId, t);
			return new ModelAndView(
					"redirect:" + appPrefix + "/userHome",
					prepareRedirectErrorMessage("Error occured when delete user!"));
		}
	}
	
	@RequestMapping(value = "/submitEditUser")
	public ModelAndView submitEditUser(Model model,
			@ModelAttribute("edit") UserBean userBean,
			HttpServletRequest request) {
		PersistUser persistUser = new PersistUser();
		UserDAO userDAO = new UserDAOImpl(this.functionDataSource,
				((PersistUser) request.getSession().getAttribute(
						MVCConstants.USER_SESSION_KEY)).getName());

		// TODO: validate
		persistUser.setId(userBean.getUserId());
		if (userBean.getPassword() != null && userBean.getPassword().length() > 0) {
			persistUser.setPassword(EncryptUtil.encryptPassword(userBean.getPassword()));
		}
		
		persistUser.setEmail(userBean.getEmail());
		if (userBean.getSysGroup() > 0) {
			PersistSysGroup persistSysGroup = new PersistSysGroup();
			persistSysGroup.setId(userBean.getSysGroup());
			persistUser.setSysGroup(persistSysGroup);
		}

		if (userBean.getBizGroup() > 0) {
			PersistBizGroup persistBizGroup = new PersistBizGroup();
			persistBizGroup.setId(userBean.getBizGroup());
			persistUser.setBizGroup(persistBizGroup);
		}
		
		try {
			userDAO.updateUser(persistUser);
			return new ModelAndView("redirect:" + appPrefix + "/userHome", prepareRedirectWarnMessage("User '" + userBean.getUserName()
					+ "' have been updated successfully!"));
		} catch (Throwable t) {
			logger.error("Error when update user, id: " + userBean.getUserId(), t);
			return new ModelAndView("redirect:" + appPrefix + "/userHome", prepareRedirectErrorMessage("Error occured when updating User '" + persistUser.getName()
					+ "' please try later!"));
		}
		
		
	}
}
